package bch.maven.plugin.guava;

import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import java.util.Iterator;

public class LargeDataExample {

    public static void main(String[] args) {
        long max = 1_000_000_000L; // 10亿数据

        // 使用 LongStream.range 生成原始 long 流，避免装箱
        long sum = LongStream.range(0, max)
                .parallel() // 并行流
                .sum();     // 求和

        System.out.println("sum = " + sum);

        // 模拟大数据的 Iterator
        Iterator<Long> iterator = new Iterator<>() {
            long i = 0;
            final long max = 1_000_000_000L; // 10亿数据

            @Override
            public boolean hasNext() { return i < max; }

            @Override
            public Long next() { return i++; }
        };

        // 转 Spliterator
        Spliterator<Long> spliterator = Spliterators.spliteratorUnknownSize(
                iterator,
                Spliterator.ORDERED | Spliterator.IMMUTABLE
        );

        // 转 Stream
        Stream<Long> stream = StreamSupport.stream(spliterator, true); // 并行流

        // 示例处理：求总和（注意大数据量时要考虑 long 溢出）
        System.out.println("sum = " + stream.reduce(0L, Long::sum));
    }
}
